/*
Version 2.2

- fix not crate edit row when sort only
- fix sort and search 
- fix  bug when has many grid in page
- add support checkBox function ...do "dataList" like this [ dataList:['checkBox','Name','Kind','BirthDate'] ]

*** can't gen from be blank table T-T ***

Suparerk@

**** need attr  key(as ID) for save and del data****
**require variable name : returnData in save and delete function**
	#ext: save
	- returnData={currentKey:saveID,valMes:{"Status":"Save Complete"}};  
	//currentKey :saved item's id, valMes: validate obj 
		
	#ext: delete
	-	returnData={currentKey:data,nextID:curentMaxID,valMes:{"Status":"Delete Complete"}} ; 
	//currentKey :deleted item's id,nextID:next ID will be create when no data, valMes: validate obj


- need table markup like this :

	<table id="firstgrid">
	 <thead>
			 <tr>
				<th width="40%">Name</th>
				<th width="40%">Kind</th>
				 <th> BirthDate</th>
			</tr>
		</thead>
	
		<!--- % foreach (var item in Model) { %--->
		<tbody>
			<tr key="itemKey0">
				<td><a href="#">Suparerk</a></td>
				<td>Tiger</td>
				<td align="center">17-December-1976</td>
			</tr>
			<tr key="itemKey1">
				<td><a href="#">Amonrat</a></td>
				<td>Cat</td>
				<td align="center">14-December-1981</td>
			</tr>
			<tr key="itemKey2">
				<td><a href="#">Burapha</a></td>
				<td>Lion</td>
				<td align="center">08-September-1984</td>
			</tr>
			<tr key="itemKey3">
				<td><a href="#">Kakmoo</a></td>
				<td>Pig	</td>
				<td align="center">01-July-1984</td>
			</tr>
		</tbody>
		
		<!--% } %-->
	
	</table>



*/
(function($) {
    jQuery.fn.twSimpleList = function(settings) {

        var holder = $(this);
        var saveButtonSet = '<span class="actionButton ui-state-default ui-state-active ui-corner-all saveRowBtn"><div class="ui-icon ui-icon-disk"></div><div class="caption">Save</div></span><span class="actionButton ui-state-default ui-state-active ui-corner-all cancelRowBtn"><div class="ui-icon ui-icon-stop"></div><div class="caption">Cancel</div></span>';
        var editButtonSet = '<div class="ui-tw-gridEditbutton"><span class="actionButton ui-state-default ui-state-focus ui-corner-all editRowBtn" title="Edit"><div class="ui-icon ui-icon-pencil"></div></span><span class="actionButton ui-state-default ui-state-error ui-corner-all delRowBtn" title="Delete"><div class="ui-icon ui-icon-close"></div></span></div>';


        var defaults = {
            dataList: ['Name', 'Kind', 'BirthDate'], // use 'checkBox' same posion of check box column 
            tableAttr: { width: '99%', align: 'center', border: 0, cellspacing: 1, cellpadding: 2 },
            keyPrefix: 'itemKey',
            editAble: true, sortAble: true,
            saveFunction: "tmpSampleData", deleteFunction: "tmpSampleData",
            validate: false, returnFunc: null, //require objValidate Plug-in
            addBtn: ".addItemBtn", searchBtn: ".searchBtn", searchInput: ".searchInput",
            saveButtonSet: saveButtonSet,
            editButtonSet: editButtonSet
        }

        var options = jQuery.extend(defaults, settings);

        ////crate editRow
        var editRow = "";
		if (options.editAble) {
			$(options.dataList).each(function(i) {
				if (options.dataList[i] != "checkBox") {
					editRow += '<td><input name="' + options.dataList[i] + '" type="text" /></td>';
				} else {
					editRow += '<td></td>';
				}
	
			});
		}

        var totalCol = $(options.dataList).size()
        //set row data id

        //install theme
        $(holder).addClass("ui-tw-gridTable ui-widget ui-corner-all ui-widget-content").attr(options.tableAttr).css({ 'white-space': 'nowrap' })
		.find("th").addClass("ui-widget-header")
		.end().find("td").addClass("ui-state-default")
		.end().find("tr:even td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });
		//add editRow to table
		if (options.editAble) {
	 		$(holder).find("tbody").after('<tr class="editRow ui-state-focus" style="display:none">' + editRow + '</tr><tr class="editRow"><td colspan="' + totalCol + '" align="center">' + options.saveButtonSet + '</td></tr>').end().find(".editRow").hide();
		}

        //editAble

        //edit
        if (options.editAble) {
            $(holder).find("tbody tr td:not(:has(input))").hover(function() {
                if (!$(holder).data('nowEdit')) {
                    //show edit button
                    var innerText = $(this).html();
                    if ($(this).find("div").size() < 1) {
                        $(this).text("").append('<div style="float:left; padding:' + ($(holder).attr('cellpadding') * 2) + 'px">' + innerText + '</div>').append(options.editButtonSet);
                    }
                    //edit
                    $(holder).find(".editRowBtn").click(function() {
                        $(this).hide();
                        $(holder).data('nowEdit', $(this).parents("tr")); //collect row 
                        $(this).parents("tr").hide().after($(holder).find('.editRow')); //hide edit row
                        $(holder).find('.editRow').removeAttr('style').show(); // show editor row
                        $(holder).find('.editRow input:eq(0)').focus();
                        $(".ui-tw-gridEditbutton").remove();
                        $(holder).find('.editRow').find('input').each(function(i) {//push txt to val
                            $(this).val($(holder).data('nowEdit').find("td:not(:has(input))").eq(i).text());
                        });
                    });
                    //del row
                    $(holder).find(".delRowBtn").click(function() {
                        if (eval(options.deleteFunction + "('" + $(this).parents("tr").attr('key') + "')")) {
                            $(this).hide();
                            $(holder).find("tbody tr:not('.editRow')").removeAttr('style'); //remove not edit row style

                            if ($(holder).find("tbody tr").size() > 1) {//not be last row to del
                                $(this).parents("tr").remove();
                            } else {
                                var newRow = $(this).parents("tr").clone(true); //tmp row 
                                newRow.find("td:not(:has(input))").text("");
                                $(holder).find("tbody tr:first").after(newRow).remove();
                                //$(this).parents("tr").remove();
                                $(holder).find("tbody tr:first").attr('key', options.keyPrefix + Number(returnData.nextID));

                                //alert("eie : "+$(holder).data('nowEdit').attr('key'));
                            }
                            $(holder).find("tbody tr:not('.editRow') td").removeAttr("style");
                            $(holder).find("tbody tr:odd td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' }); // re set alternative

                            //alert("Mode --> Delete -->"+$(this).parents("tr").attr('key'));
                            //**************************************************************require objValidate Plug-in
                            if (options.validate) {
                                $(holder).before('<div class="ui-tw-gridMessages" />')
                                if (options.returnFunc != null) { var returnFunc = options.returnFunc + "()" } else { var returnFunc = null };
                                $(holder).prev('div.ui-tw-gridMessages').objValidate({ throwObj: returnData.valMes, removeAble: 'auto', returnTo: returnFunc });
                            }
                            alert(returnData.currentKey + " : deleted");
                        } else {

                            //******************************************************require objValidate Plug-in
                            if (options.validate) {
                                $(holder).before('<div class="ui-tw-gridMessages" />')
                                if (options.returnFunc != null) { var returnFunc = options.returnFunc + "()" } else { var returnFunc = null };
                                $(holder).prev('div.ui-tw-gridMessages').objValidate({ throwObj: returnData.valMes, removeAble: 'auto', returnTo: returnFunc });
                            }
                            $(".cancelRowBtn").click();

                        }
                    });
                }
            }, function() {
                if (!$(holder).data('nowEdit')) {
                    var innerText = $(this).find("div:first").html();
                    $(".ui-tw-gridEditbutton").remove();
                    $(this).find("div").remove();
                    $(this).html(innerText);
                }
            });
            //add
            $(options.addBtn).click(function() {
                if (!$(holder).data('nowEdit')) {

                    $(holder).find("tbody tr:first").before($(holder).find('.editRow')); //hide edit row
                    $(holder).find('.editRow').removeAttr('style').show(); // show editor row
                    $(holder).find('.editRow input:eq(0)').focus();
                    $(holder).find('.editRow').find('input').each(function(i) {//push txt to val
                        $(this).val("");
                    });
                    var newRow = $(holder).find("tbody tr:last").clone(true);
                    newRow.find("td").removeAttr('style'); //setting newRow
                    $(holder).data('nowEdit', newRow)
                    $(holder).data('nowEdit').attr('key', 0);
                };

            });
            //save
            $(holder).find(".saveRowBtn").click(function() {
                //	alert(options.saveFunction+"('"+$(holder).data('nowEdit').attr("key")+"')")
                if (eval(options.saveFunction + "('" + $(holder).data('nowEdit').attr('key') + "')")) {

                    if ($(holder).data('nowEdit').attr('key') == 0) {//if add new
                        var newRow = $(holder).find("tbody tr:last").clone(true);

                        //newRow.find("td").text("");	
                        newRow.find("td").removeAttr('style'); //setting newRow
                        $(holder).find("tbody tr:last").after(newRow);
                        $(holder).data('nowEdit', $(holder).find("tbody tr:last")); //set curent edit tr
                        //newRow.attr('key',"itemKey"+Number(returnData.currentKey));
                        $(holder).data('nowEdit').attr('key', options.keyPrefix + returnData.currentKey);

                        $(holder).find("tbody tr:odd td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });

                        alert('new : ' + options.keyPrefix + returnData.currentKey + " : save");
                    } else {
                        $(holder).data('nowEdit').show();
                        alert(returnData.currentKey + " : save");
                    }

                    $(holder).find('.editRow').hide();
                    $(holder).data('nowEdit').find('td:not(:has(input[type="checkbox"]))').each(function(i) {//push val to txt
                        $(this).find(":last").text($(holder).find('.editRow input').eq(i).val());
                    });

                    //******************************************************require objValidate Plug-in
                    if (options.validate) {
                        $(holder).before('<div class="ui-tw-gridMessages" />')
                        if (options.returnFunc != null) { var returnFunc = options.returnFunc + "()" } else { var returnFunc = null };
                        $(holder).prev('div.ui-tw-gridMessages').objValidate({ throwObj: returnData.valMes, removeAble: 'auto', returnTo: returnFunc });
                    }

                    //eval(options.returnFunc+'("'+returnData.currentKey+'" , "'+ returnData.valMes+'")');
                    $(holder).data('nowEdit').attr("key", returnData.Key);
                    $(holder).data('nowEdit', null);

                    $(holder).find('tbody').after($(holder).find('tbody tr.editRow'))//move edit out

                } else {

                    //******************************************************require objValidate Plug-in
                    if (options.validate) {
                        $(holder).before('<div class="ui-tw-gridMessages" />')
                        if (options.returnFunc != null) { var returnFunc = options.returnFunc + "()" } else { var returnFunc = null };
                        $(holder).prev('div.ui-tw-gridMessages').objValidate({ throwObj: returnData.valMes, removeAble: 'auto', returnTo: returnFunc });
                    }

                    $(".cancelRowBtn").click();

                }

            });
            //end save
            //cancel
            $(holder).find(".cancelRowBtn").click(function() {
                //if($(holder).data('nowEdit').attr('key') == 0){
                $(holder).data('nowEdit').show();
                $(holder).find('.editRow').hide();
                $(holder).data('nowEdit', null);
                //}
                $(holder).find('tbody').after($(holder).find('tbody tr.editRow'))//move edit out
            });
            //end cancel
        }
        //end editable
        //search
        $(options.searchBtn).click(function() {
            $(holder).find("tr:not(.editRow)").data('found', false)//remove data found
            if (!$(options.searchInput).val()) { // if not val
                $(holder).find("tr:not(.editRow)").show();
            } else {
                $(holder).find('td').each(function() {
                    var thisText = $(this).text();
                    thisText = thisText.toLowerCase();
                    var searchText = $(options.searchInput).val();
                    searchText = searchText.toLowerCase();

                    if (thisText.indexOf(searchText) == -1 && !$(this).parents("tr:not(.editRow)").data('found')) { //if not found this td
                        $(this).parents("tr:not(.editRow)").hide();
                    } else {
                        $(this).parents("tr:not(.editRow)").data('found', true); //if found set data and show
                        $(this).parents("tr:not(.editRow)").show();
                    }
                });
            }
        });
        ///end search
        //sort
        if (options.sortAble) {
            $(holder).find("thead th").css({ cursor: 'pointer' });
            $(holder).find("thead th").each(function(i) {
                //sorting with no input
                if ($(this).find("input").size() == 0) {
                    $(this).toggle(function() {
                        var tmpSort = [];
                        var thisIndex = i;
                        $(holder).find('tbody tr').each(function(j) {
                            tmpSort.push($(holder).find('tbody tr:eq(' + j + ') td:eq(' + thisIndex + ')').text());
                        });
                        tmpSort.sort();
                        //alert(tmpSort);
                        $(tmpSort).each(function(k) {// map td text 
                            $(holder).find('tbody tr').find('td:eq(' + thisIndex + ')').each(function() {
                                var lookAtRow = $(this);
                                //alert(tmpSort[k]+":"+$(lookAtRow).text());
                                if ($(lookAtRow).text() == tmpSort[k]) {//move to top
                                    //alert($(this).parents("tr").text());
                                    var newRow = $(lookAtRow).parent().clone(true);
                                    $(lookAtRow).parent().remove()
                                    $(holder).find("tbody").append(newRow);
                                }
                            });
                        });
                        $(this).find(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-n");
                        $(holder).find("tbody tr:not('.editRow') td").removeAttr("style");
                        $(holder).find("tbody tr:even td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });

                    }, function() {// toggle sort
                        var tmpSort = [];
                        var thisIndex = i;

                        $(holder).find('tbody tr').each(function(j) {
                            tmpSort.push($(holder).find('tbody tr:eq(' + j + ') td:eq(' + thisIndex + ')').text());
                        });
                        tmpSort.sort();
                        tmpSort.reverse();
                        //alert(tmpSort)
                        $(tmpSort).each(function(k) {// map td text 
                            $(holder).find('tbody tr').find('td:eq(' + thisIndex + ')').each(function() {
                                var lookAtRow = $(this);
                                //alert(tmpSort[k]+":"+$(lookAtRow).text());
                                if ($(lookAtRow).text() == tmpSort[k]) {//move to top
                                    //alert($(this).parents("tr").text());
                                    var newRow = $(lookAtRow).parent().clone(true);
                                    $(lookAtRow).parent().remove();
                                    $(holder).find("tbody").append(newRow);
                                }
                            });
                        });
                        $(this).find(".ui-icon").removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s");
                        $(holder).find("tbody tr:not('.editRow') td").removeAttr("style");
                        $(holder).find("tbody tr:odd td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });

                    });
                    //sort icon
                    $(this).hover(function() {
                        if (!$(this).find(".ui-icon").size()) {
                            $(this).wrapInner('<div style="float:left;margin-left:10px" class="caption"></div>');
                            $(this).append('<div style="float:left; margin-left:5px" class="ui-icon ui-icon-triangle-1-n">');
                        } else {
                            $(this).find(".ui-icon").show();
                        }
                    }, function() {
                        var tmpText = $(this).text();
                        $(this).find(".caption").remove();
                        $(this).text(tmpText);
                        $(this).find(".ui-icon").hide();
                    });
                    //
                }
                //end no input
            });
        }
        
        //end sort

    } //end plug-in
})(jQuery);

//sample function
function tmpSampleData(){
	returnData={currentKey:'itemTest',nextID:5,valMes:{"Status":"Complete"}};
	return returnData,true;
}

function tmpVal(MES){alert(MES)}

